var ejs = require('ejs');
var fs = require('fs');
var querystring = require('querystring');
var app = {
    //login
    login: function (req, res) {
        var list = ['111', '222', '333', '444'];
        var data = "这是后台返回的数据哦";
        ejs.renderFile('./07getpost/views/login.ejs', {
            msg: data,
            list: list
        }, function (err, data) {
            res.end(data);
        });
    },
    main: function (req, res) {
        if (req.method == 'GET') {
            var params = url.parse(req.url, true).query;
            console.log(req.url);
            ejs.renderFile('./07getpost/views/main.ejs', {
                username: params.username,
                password: params.password,
            }, function (err, data) {
                res.end(data);
            });
        } else {
            var postStr = '';
            req.on('data', function (chunk) {
                // chunk 默认是一个二进制数据，和 data 拼接会自动 toString
                postStr += chunk;
            });
            req.on('end', function (err, chunk) {
                try {
                    postStr = JSON.parse(postStr);
                } catch (e) {
                    postStr = querystring.parse(postStr);
                    console.log(postStr);
                }
                ejs.renderFile('./07getpost/views/main.ejs', {
                    username: postStr.username,
                    password: postStr.password
                }, function (err, data) {
                    res.end(data);
                });
            })

        }
    },
    register: function (req, res) {
        var data = "这是注册页面也是注册路由";
        var htmlStr = "<h2>这是html标签</h2>";
        ejs.renderFile('./07getpost/views/register.ejs', {
            msg: data,
            htmlStr: htmlStr
        }, function (err, data) {
            res.end(data);
        });
    },
    index: function (req, res) {
        var list = ['111', '222', '333', '444'];
        var data = "这是后台返回的数据哦";
        ejs.renderFile('./07getpost/views/index.ejs', {
            msg: data,
            list: list
        }, function (err, data) {
            res.end(data);
        });
    }
}

module.exports = app;